package com.itheima.config;

import com.itheima.filter.JWTAuthenticationFilter;
import com.itheima.filter.JWTAuthorizationFilter;
import com.itheima.filter.JwtProperties;
import com.itheima.userdetailservice.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)//开发注解权限配置
@EnableConfigurationProperties(JwtProperties.class)
public class MyWebSecurityAdapter extends WebSecurityConfigurerAdapter {



    @Autowired
    private JwtProperties properties;


    @Autowired
    private MyUserDetailService myUserDetailService;


    //   重写默认 认证管理器  配置指定内存版账号和密码
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //数据库版用户认证
        auth.userDetailsService(myUserDetailService).passwordEncoder(createPasswordEncoder());

    }

    //使用加密器对象 对密码进行加密
    private PasswordEncoder createPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().
                disable().
                addFilter(new JWTAuthenticationFilter(super.authenticationManager(),properties))
                .addFilter(new JWTAuthorizationFilter(super.authenticationManager(),properties))
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS); // 禁用session

    }
}
